package com.zm.devmag.filter;

import java.io.IOException;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;



public class EncodeFilter implements Filter {

	/*private String encode;*/

	@Override
	public void destroy() {}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if(((HttpServletRequest) request).getMethod().equalsIgnoreCase("POST")){
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			HttpServletRequest req = (HttpServletRequest)request;
			String uri = req.getRequestURI();
			if(uri.contains("back")){
				chain.doFilter(request, response);
			}else{
				chain.doFilter(new XSSHttpServletRequest((HttpServletRequest) request), response);
			}
		}else {
			chain.doFilter(request, response);
		}
	
		
	}
	
	@Override
	public void init(FilterConfig config) throws ServletException {
		/*this.encode = config.getServletContext().getInitParameter("encode");*/
	}
	

	private class XSSHttpServletRequest extends HttpServletRequestWrapper{
		private  HttpServletRequest request = null;
	
		public XSSHttpServletRequest(HttpServletRequest request) {
			super(request);
			this.request = request;
		}
		
		@Override
		public Map<String,String[]> getParameterMap() {				
			Map<String,String[]> map = request.getParameterMap();
				for(Map.Entry<String, String[]> entry : map.entrySet()){
					String [] vs = entry.getValue();
					for(int i=0;i<vs.length;i++){
						vs[i] = vs[i].replaceAll("<", "&lt").replaceAll(">", "&gt");
					}
				}
			return map;
		}
		
		@Override
		public String[] getParameterValues(String name) {
			return getParameterMap().get(name);
		}
		
		@Override
		public String getParameter(String name) {
			return getParameterValues(name) == null ? null : getParameterValues(name)[0];
		}
		
	} 

}
